#include <WiFi.h>
#include <TFT_eSPI.h>

#define BLK 5
#define PORT 8765
#define BUFFER_SIZE 1024
#define WIDTH 240
#define HEIGHT 240
#define FRAME_SIZE (WIDTH * 2)  // 每次传输一行数据，RGB565每像素2字节
#define TAIL_BYTE_1 0xAA
#define TAIL_BYTE_2 0xBB
#define TAIL_BYTE_3 0xCC

const char* ssid = "helloworld";
const char* password = "12345678";

WiFiServer server(PORT);
WiFiClient client;

TFT_eSPI tft = TFT_eSPI();
uint8_t buffer[BUFFER_SIZE];
uint8_t frame[FRAME_SIZE + 3];  // 每行数据加上3字节尾部校验

void setup() {
  Serial.begin(115200);

  tft.init();
  tft.setRotation(2);
  tft.fillScreen(TFT_BLACK);
  pinMode(BLK, OUTPUT);
  digitalWrite(BLK, HIGH);

  WiFi.begin(ssid, password);
  Serial.print("连接 WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\n✅ WiFi 已连接！");
  Serial.println(WiFi.localIP());

  server.begin();
  Serial.printf("📡 正在监听端口 %d...\n", PORT);
}

void loop() {
  
  if (!client || !client.connected()) {
    client = server.available();
    if (client) {
      Serial.println("📥 客户端已连接！");
      client.write("ok");
    }
    return;
  }
  

  // 每次接收一行数据
  if (client.available() < FRAME_SIZE + 3) return;

  size_t received = 0;
   Serial.println("接受到数据");
  while (received < FRAME_SIZE + 3) {
    size_t to_read = min((size_t)BUFFER_SIZE, (size_t)(FRAME_SIZE + 3 - received));
    int read_bytes = client.read(buffer, to_read);
    if (read_bytes <= 0) continue;
    memcpy(frame + received, buffer, read_bytes);
    received += read_bytes;
  }

  // 校验尾部字节
  if (frame[FRAME_SIZE] != TAIL_BYTE_1 || frame[FRAME_SIZE + 1] != TAIL_BYTE_2 || frame[FRAME_SIZE + 2] != TAIL_BYTE_3) {
    Serial.println("⚠️ 帧尾错误，丢弃帧");
    client.write("ok");
    return;
  }

  // 将接收到的这一行数据显示到屏幕上
  static int y_pos = 0;
  if (y_pos < HEIGHT) {
    Serial.printf("🖼️ 显示第 %d 行\n", y_pos);
    // 接受 uint16_t 数组
    uint16_t* pixel_data = (uint16_t*)frame;
    tft.pushImage(0, y_pos, WIDTH, 1, pixel_data);
    y_pos++;
  }

  // 如果显示完所有行，重置y_pos以重新开始显示
  if (y_pos >= HEIGHT) {
    y_pos = 0;
    tft.fillScreen(TFT_BLACK);  // 清屏
  }

  client.write("ok");
}